package csel.model;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class GameFactory implements java.io.Serializable
{
	private static final long serialVersionUID = 1L;

	public static boolean newGame(Occupation occupation, String name, Model model) throws IOException
	{
		GameGlobals globals = new GameGlobals();
		
		Map myMap;
		try
		{
			myMap = loadMap("defaultMap", globals);
		}
		catch (IOException ex)
		{
			//System.err.println(ex.);
			ex.printStackTrace();
			throw ex;
		}
		
		Entity player = new Entity(globals, occupation);
		player.setName(name);
		
		Tile myTile = myMap.getTile(5, 4);
		myTile.setEntity(player);
		player.setLocation(myTile);
		
		ArrayList<Entity> entityList = new ArrayList<Entity>();
		entityList.add(player);
		GameData gameData = GameData.makeGameData(globals, entityList, player, myMap);
		model.set_gameData(gameData);
	
		player.addObserver(myMap);
		
		System.out.printf("[MODEL] Constructed new game (%s,%s,%s).\n",
				myTile, player.getLocation(), gameData.get_playerEntity());
		player.getInventory().setHasChanged(true);
		
		/* START THE GAME ALREADY */
		globals.getChronoTrigger().start();
		
		return true;
	}
	
	private static Map loadMap(String filepath, GameGlobals globals)
		throws FileNotFoundException, IOException
	{
		FileInputStream fileIn;
		ObjectInputStream serializer;
		Map map;

		fileIn = new FileInputStream(filepath);
		serializer = new ObjectInputStream(fileIn);

		try
		{
			map = (Map) serializer.readObject();
		} catch (ClassNotFoundException ex)
		{
			throw new IOException("Invalid save file data.", ex);
		}

		serializer.close();
		fileIn.close();
		
		/* go through and hook up all area effects with GameGlobals */
		Tile[][] tiles = map.getTileMatrix();
		for (int i = 0; i < tiles.length; i++)
		{
			for (Tile t : tiles[i])
			{
				if (t == null)
					continue;
				
				AreaEffect ae = t.getAreaEffect(); 
				
				if (ae != null)
					ae.attach(globals);
			}
		}

		return map;
	}
}
